/**
 * 说明： 是一个按钮类自定义控件的示例
 * */
var object;
(function(factory){
    var nameSpace = 'field_1267193202406111629';
    if(!window[nameSpace]){
        var Builder = factory();
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
        window[nameSpace].isNotNull = function (obj) {
            return true;
        };
    }
})(function(){
    /**
     * 构造函数
     * @param options
     * @constructor
     */
    function App(options) {
        var self = this;
        //初始化参数
        self.initParams(options);
        //初始化dom
        self.initDom();
        //事件
        self.events();
    }

    App.prototype = {
        initParams : function (options) {
            object = options;
            var self = this;
            self.adaptation = options.adaptation;
            self.privateId = options.privateId;
            self.messageObj = options.getData;
            self.preUrl = options.url_prefix;
        },
        initDom : function () {
            var self = this;
            dynamicLoading.css(self.preUrl + 'css/baiduOcrBtn.css');
            self.appendChildDom();
        },
        events : function () {
            var self = this;
            // 监听是否数据刷新
            self.adaptation.ObserverEvent.listen('Event' + self.privateId, function() {
                self.messageObj = self.adaptation.childrenGetData(self.privateId);
                self.appendChildDom();
            });
        },
        appendChildDom : function () {
            var self = this;
            var domStructure = '<form style="display:none" action="/seeyon/rest/jssdk/importInvoiceBaiDuData" method="post"  enctype="multipart/form-data" id="myForm">'+
                '<input type="file" multiple="true" id="file" name="file" style="display:none">'+
                '</form>'+
                '<section class="customButton_box_content">'+
                '<div class="customButton_class_box '+ self.privateId + '" title="' + self.messageObj.display.escapeHTML() + '">'+ self.messageObj.display.escapeHTML() +'</div>'+
                '</section>'
            document.querySelector('#' + self.privateId).innerHTML = domStructure;

            var jumpFun = function() {
                //点击上传附件
                document.getElementById('file').click();
            };
            //监听文件上传
            document.getElementById('file').addEventListener('change', function(event) {
                csdk.util.openMask()
                //获取表单主表id
                var subData = csdk.core.getFormData()

                //获取自定义控件的配置信息
                var fieldsMap = subData.formmains[object.field.tableName][object.getData.id].customFieldInfo.customParam.mapping

                var masterId = subData.metadata.content.contentDataId;
                console.log(masterId)
                var fileList = event.target.files
                if (fileList.length<1) {
                    csdk.util.closeMask()
                    return;
                }
                var form = new FormData();
                for (var i = 0; i < fileList.length; i++) {
                    // form.append('file', fileList[i]); //支持多文件上传
                    form.append("files",fileList[i]);
                }
                form.append("masterId",masterId)
                form.append("fieldsMap",JSON.stringify(fieldsMap))
                //调用后端接口
                $.ajax({
                    url: "/seeyon/rest/jssdk/importInvoiceBaiDuData",
                    data: form,
                    type: "POST",
                    processData: false,
                    contentType: false,
                    error: function (data) {

                    },
                    success: function (data) {
                        data = JSON.parse(data);
                        if(data.code === '200'){
                            event.target.value = null;
                            csdk.util.closeMask()
                            //回写表单数据
                            var filedInfoData = data.data
                            var masterDataList = filedInfoData.master
                            var masterFieldDataList = []
                            //获取明细表数据
                            var subDataList = filedInfoData.sub
                            if(masterDataList.length>0){
                                for(var i = 0;i<masterDataList.length;i++){
                                    var atts = masterDataList[i].fieldData.atts
                                    if(atts !== undefined){
                                        var fieldId = masterDataList[i].fieldId
                                        var tableName = masterDataList[i].formTableName
                                        //组装回写附件数据
                                        var formData = [{
                                            tableName:tableName,
                                            tableCategory:'formmain',
                                            handlerMode:'add',
                                            fieldName: fieldId,
                                            addAttchmentData: atts,
                                            deleteAttachmentData:[]
                                        }]
                                        // self.adaptation.backfillFormAttachment(formData,self.privateId)
                                        window.thirdPartyFormAPI.backfillFormAttachment(formData);
                                    }else{
                                        masterFieldDataList.push(masterDataList[i])
                                    }
                                }
                            }
                            // if(masterFieldDataList.length>0){
                            //     csdk.core.setFieldData(masterDataList);
                            // }

                            //回写明细
                            var tableDatas = Object.groupBy(subDataList,({tableName})=>tableName)
                            var keys = Object.keys(tableDatas)
                            for(var t = 0;t<keys.length;t++){
                                //获取需要新增行的id
                                var records = []
                                var tableDataList = tableDatas[keys[t]]
                                for(var i=0;i<tableDataList.length;i++){
                                    //行id
                                    var recordId = tableDataList[i].uuid
                                    records.push(recordId)
                                }
                                var options = {
                                    tableName: keys[t],
                                    posRecordId: null,
                                    addRecords: records
                                }
                                //创建明细行数据，并回写字段信息
                                var tableIndex = 0
                                csdk.core.addRecords(options,function (err, newRecord) {
                                    if (err) {
                                        console.log("添加失败：" + err)
                                        return;
                                    }
                                    var tableDataList =tableDatas[keys[tableIndex]]
                                    //添加成功，取得新记录的id
                                    for (var i = 0; i < newRecord.length; i++) {
                                        //给每行数据字段赋值
                                        var hdata = tableDataList[i].hData
                                        for (var j = 0; j < hdata.length; j++) {
                                            hdata[j].recordId = newRecord[i]
                                        }
                                        csdk.core.setFieldData(hdata);
                                    }
                                    tableIndex += 1;
                                })

                                //删除第一行
                                var forms = subData.formsons
                                var formsKey = Object.keys(forms)
                                for(var k = 0;k<formsKey.length;k++){
                                    var tableData = forms[formsKey[k]];
                                    var formsTableName = tableData.tableName
                                    if(formsTableName === keys[t]){
                                        //删除第一行
                                        var tableRe = tableData.records[0]
                                        //判断是否是自动生成第一行
                                        var tableLists = tableRe.lists
                                        var tableListsKey = Object.keys(tableLists)
                                        var Xkey = tableLists[tableListsKey[0]].Xkey
                                        if(Xkey !== undefined){
                                            var recordList = []
                                            recordList.push(tableRe.recordId)
                                            csdk.core.deleteRecord({tableName:keys[t],records:recordList},function (err){
                                                if (err) {
                                                    console.log("删除行失败！"+tableRe.recordId)
                                                }else{
                                                    console.log("删除行成功！"+tableRe.recordId)
                                                }
                                            })
                                        }
                                    }
                                }
                            }
                            csdk.util.alert("识别成功！！！！！")
                        }else{
                            event.target.value = null;
                            csdk.util.closeMask()
                            csdk.util.alert(data.message)
                        }
                    }
                });
            })
            document.querySelector('.' + self.privateId).removeEventListener('click',jumpFun);
            document.querySelector('.' + self.privateId).addEventListener('click',jumpFun);
            //渲染隐藏权限
            if (self.messageObj.auth === 'hide') {
                document.querySelector('#' + self.privateId).innerHTML = '<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>';
            }
        },

        dealCdtMapping : function (opt) {
            $.ajax({
                url: '/seeyon/rest/cap4/formquerybtn/dealCdtMapping?formId=' + opt.formId + '&fieldName=' + opt.fieldName + '&formDataId=' + opt.formDataId + '&formSubDataId=' + opt.formSubDataId + '&designId=' + opt.designId,
                success: function (data) {
                    if(opt.callback && typeof opt.callback === 'function')
                        opt.callback.apply();
                },
                error: function (e) {
                    if(e.message){
                        top.$.error(e.message);
                    }else{
                        top.$.error('处理筛查条件出错...');
                    }
                }
            });
        }
    };



    var dynamicLoading = {
        css: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = path;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link);
        },
        js: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = path;
            script.type = 'text/javascript';
            head.appendChild(script);
        }
    }

    return App;
});
